package net.tarine.gastronomi.client;

import net.tarine.gastronomi.client.services.GasService;
import net.tarine.gastronomi.client.services.GasServiceAsync;
import net.tarine.gastronomi.client.widgets.MenuPanel;
import net.tarine.gastronomi.client.widgets.MessagePanel;
import net.tarine.gastronomi.shared.to.GasTo;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.SimplePanel;

public class UiSingleton implements ValueChangeHandler<String> {

	private static UiSingleton instance = null;

	private GasTo gas = null;
	
	private MenuPanel menuPanel;
	private FlowPanel rightPanel;
	private MessagePanel messagePanel;
	private SimplePanel contentPanel;
	
	private UiSingleton() {
		initUi();
	}
	
	public static UiSingleton get() {
		if (instance == null) {
			instance = new UiSingleton();
		}
		return instance;
	}
	
	private void initUi() {
		//header
		//RootPanel.get("header").add(messagePanel);
		//left-column
		menuPanel = new MenuPanel();
		RootPanel.get("left-column").add(menuPanel);
		//right-column
		rightPanel = new FlowPanel();
		messagePanel = new MessagePanel();
		rightPanel.add(messagePanel);
		contentPanel = new SimplePanel();
		rightPanel.add(contentPanel);
		RootPanel.get("right-column").add(rightPanel);
		History.addValueChangeHandler(this);
		//carica il gas
		loadActiveGas();
	}
	
	@Override
	public void onValueChange(ValueChangeEvent<String> event) {
		HistoryMgr.loadContent(History.getToken());
	}
	
	public SimplePanel getContentPanel() {
		return contentPanel;
	}
	
	public MenuPanel getMenuPanel() {
		return menuPanel;
	}
	
	public GasTo getGas() {
		return gas;
	}
	
	public void setGas(GasTo gas) {
		this.gas = gas;
		if (menuPanel != null) {
			menuPanel.setGas(gas);
		}
	}
	
	
	//messaging
	
	public void addInfo(String message) {
		messagePanel.addInfo(message);
	}
	public void addWarning(String message) {
		messagePanel.addWarning(message);
	}
	public void addError(String message) {
		messagePanel.addError(message);
	}
	public void addError(Throwable e) {
		messagePanel.addError(e.getMessage());
	}

	
	
	//AsyncMethods
	
	
	
	private void loadActiveGas() {
		AsyncCallback<GasTo> callback = new AsyncCallback<GasTo>() {
			@Override
			public void onFailure(Throwable caught) {
				UiSingleton.get().addError(caught);
			}
			@Override
			public void onSuccess(GasTo result) {
				setGas(result);
			}
		};
		GasServiceAsync gasService = GWT.create(GasService.class);
		gasService.findGas(callback);
	}
}
